package org.dev.vlp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dev.vlp.constants.LanguageEnum;
import org.dev.vlp.entity.Word;
import org.dev.vlp.entity.WordCollection;
import org.dev.vlp.exception.ApiException;
import org.dev.vlp.service.StatisticsService;
import org.dev.vlp.service.WordCollectionService;
import org.dev.vlp.mapper.WordCollectionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
* @author 86184
* @description 针对表【vlp_word_collection】的数据库操作Service实现
* @createDate 2023-01-16 21:52:33
*/
@Service
public class WordCollectionServiceImpl extends ServiceImpl<WordCollectionMapper, WordCollection>
    implements WordCollectionService{

    @Autowired
    private WordCollectionMapper wordCollectionMapper;

    @Autowired
    private StatisticsService statisticsService;

    @Override
    public boolean wordIsCollected(long userId, long wordId) {
        int lan = statisticsService.getLan((int)userId);
        QueryWrapper<WordCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("word_id", wordId)
                .eq("lan_id",lan);
        return wordCollectionMapper.selectOne(queryWrapper) != null;
    }

    @Override
    public void collectWord(long userId, long wordId) {
        // 查询单词是否已存在
        if (wordIsCollected(userId, wordId)) {
            throw new ApiException("单词已收藏");
        }

        // 收藏单词
        WordCollection collection = new WordCollection();
        collection.setUserId(userId);
        collection.setWordId(wordId);

        int lan = statisticsService.getLan((int)userId);
        collection.setLanId(lan);
        wordCollectionMapper.insert(collection);
    }

    @Override
    public void cancelCollectWord(long userId, long wordId) {
        int lan = statisticsService.getLan((int)userId);
        QueryWrapper<WordCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("word_id", wordId)
                .eq("lan_id",lan);
        wordCollectionMapper.delete(queryWrapper);
    }

    @Override
    public List<Word> getCollectionList(long userId) {
        int lan = statisticsService.getLan((int)userId);
        LanguageEnum languageEnum = LanguageEnum.get(lan);
        String tableName = languageEnum.getWordTableEnum().getTableName();
        List<Word> collections = wordCollectionMapper.getCollectionList(userId,lan,tableName);
        Collections.reverse(collections);
        return collections;
    }
}




